package com.google.appengine.a4ieve.servlets.resources;

import com.google.appengine.a4ieve.Const;
import com.google.appengine.a4ieve.Helper;
import com.google.appengine.a4ieve.entities.AchievementWrapper;
import com.google.appengine.api.datastore.*;
import com.google.appengine.api.users.UserServiceFactory;
import org.json.JSONObject;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.logging.Logger;

public class ApproveAchievementServant implements Servant{

    private static final Logger LOG = Logger.getLogger(ApproveAchievementServant.class.getName());

    @Override
    public void process(HttpServletRequest req, HttpServletResponse resp) {
        String currentUser = Helper.cropEmailId(UserServiceFactory.getUserService().getCurrentUser().getEmail());
        JSONObject object = (JSONObject)req.getAttribute(Const.INNER_JSON);
        String entityKey = object.getString(Const.KEY);
        String entityProposedBy = object.getString(Const.USER);
        if (entityProposedBy.equals(currentUser)) {
            throw new IllegalArgumentException("You cannot approve achievements you proposed yourself");
        }
        DatastoreService service = DatastoreServiceFactory.getDatastoreService();
        try {
            Entity e = service.get(KeyFactory.stringToKey(entityKey));
            e.setProperty(AchievementWrapper.APPROVED_BY, currentUser);
            service.put(e);
            Const.SUCCESS_OBJECT.write(resp.getWriter());
        } catch(EntityNotFoundException e) {
            LOG.severe("Entered entity not found " + entityKey);
        } catch (IOException e) {
            LOG.severe("Exception while writing JSON data");
        }
    }
}
